package com.fingerchar.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fingerchar.core.base.service.IBaseService;
import com.fingerchar.db.dao.FcUsdtRechargeMapper;
import com.fingerchar.db.domain.TtCalRecord;
import com.fingerchar.db.domain.TtUsdtRecharge;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * @author tangzf
 * @date 2022/9/5
 */
@Service
public class TtUsdtRechargeService {
    @Resource
    private IBaseService baseService;
    @Resource
    FcUsdtRechargeMapper fcUsdtRechargeMapper;

    public TtUsdtRecharge getByHash(String hash) {
        QueryWrapper<TtUsdtRecharge> wrapper = new QueryWrapper<>();
        wrapper.eq("hash", hash);
        return this.baseService.getByCondition(TtUsdtRecharge.class, wrapper);
    }

    /**
     * 查询昨天的总收益（用于 汇总查询平台的收益）
     * @return
     */
    public BigInteger sumByAddressUser(String userAddress){
        Date now = DateUtil.parse(DateUtil.format(new Date(), "yyyy-DD-dd"));
        Date yesterday = DateUtil.parse(DateUtil.format(DateUtils.addDays(new Date(), -1), "yyyy-DD-dd"));
        QueryWrapper<TtUsdtRecharge> wrapper = new QueryWrapper<>();
        //大于等于昨天
        wrapper.ge("create_time", yesterday.getTime())
                //小于今天
                .lt("create_time", now.getTime())
                .eq("user_address", userAddress);
        List<TtUsdtRecharge> usdtRecharges = baseService.findByCondition(TtUsdtRecharge.class, wrapper);
        if(CollectionUtil.isEmpty(usdtRecharges)){
            return BigInteger.ZERO;
        }else {
            return usdtRecharges.stream().map(TtUsdtRecharge::getAmount).reduce(BigInteger.ZERO, BigInteger::add);
        }

    }

    public int insert(TtUsdtRecharge ttUsdtRecharge){
        return baseService.save(ttUsdtRecharge);
    }


    int insert(String hash, String address, BigInteger amount, String optType) {
        TtUsdtRecharge fcUsdtRecharge = TtUsdtRecharge.builder()
                .hash(hash)
                .userAddress(address)
                .amount(amount)
                .optType(optType)
                .build();
        return baseService.save(fcUsdtRecharge);
    }


}
